﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BrandonHaynes.Membership.Factors.PromptControls
	{
	/// <summary>
	/// A control that displays a message and queries for a user's (usually one-time) password
	/// </summary>
	public class PasswordPrompt : Control
		{
		/// <summary>
		/// The text message to display in the prompt
		/// </summary>
		public string Text { get; set; }
		/// <summary>
		/// The CSS class of the message and password input
		/// </summary>
		public string CssClass { get; set; }

		public PasswordPrompt()
			{ }

		public PasswordPrompt(string id, string text, string cssClass)
			: this()
			{
			ID = id;
			Text = text;
			CssClass = cssClass; 
			}

		public PasswordPrompt(string id, IDictionary<string, string> attributes)
			: this(id, attributes.GetValueOrDefault("text", "Enter your one-time password:"), attributes.GetValueOrDefault("cssClass", "PasswordPrompt"))
			{ }

		protected override void OnInit(EventArgs e)
			{
			base.OnInit(e);

			// Create our message prompt
			var label = new Label() { Text = this.Text, CssClass = this.CssClass };
			Controls.Add(label);

			// Create our password input
			var prompt = new TextBox() 
				{ ID = MultifactorControl.PromptPrefix + ID, 
				  CssClass = this.CssClass, 
				  TextMode = TextBoxMode.Password };
			Controls.Add(prompt);

			// Don't tell anyone I'm doing this.  Since we're creating our controls during databinding,
				// we're well past the first- and second-try Page.ProcessPostData step, and the controls
				// we create have missed the train.  We manually catch up.
				// Note that this fact will significantly affect the sophistication of controls we instantiate
				// here.  This is acceptable -- these factor prompts should remain very simple.  Don't do anything
				// very complex with these!
			((IPostBackDataHandler)prompt).LoadPostData(prompt.UniqueID, Page.Request.Form);
			}
		}
	}
